package minatest;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
import org.apache.mina.common.IoConnectorConfig;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.WriteFuture;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.SocketConnector;

public class TestClient 
{
	public static void main(String args[])throws Exception
	{
		IoConnector connector=new SocketConnector();
		((IoConnectorConfig)connector.getDefaultConfig()).setConnectTimeout(10000);
		ConnectFuture future=connector.connect(new InetSocketAddress("localhost", 5222),new MyHandler());		
		future.join();		
		System.out.println("finished");
	}
	
}

class MyHandler extends IoHandlerAdapter
{
	public void sessionCreated(IoSession session)throws Exception
	{
		ProtocolCodecFactory codec;
	    codec = new TextLineCodecFactory(Charset.forName("UTF-8"));
	    session.getFilterChain().addLast("protocolFilter", new ProtocolCodecFilter(codec));
	}
	
	@Override
	public void sessionOpened(IoSession session)
	{
		System.out.println("sending");
		WriteFuture future=session.write("dakiler");
		future.join();
		if(future.isWritten())
		{
			System.out.println("ok");
		}
		else
		{
			System.out.println("error in sending");
		}
		System.out.println("sent");
	}
	@Override
	public void messageReceived(IoSession session,Object msg)throws Exception
	{
		System.out.println("receive in client");
		System.out.println(msg.toString());
	}
	@Override
	public void exceptionCaught(IoSession session,Throwable t)
	{
		t.printStackTrace();
	}
}
